package com.lgl.mes.barcode.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.lgl.mes.barcode.request.spBarcodeBatchAddReq;
import com.lgl.mes.barcode.request.spBarcodeReq;
import com.lgl.mes.barcode.service.impl.SpBarcodeServiceImpl;
import com.lgl.mes.common.Result;
import com.lgl.mes.common.util.BarcodeUtil;
import com.lgl.mes.common.util.log.SysLog;
import com.lgl.mes.barcode.entity.SpBarcode;
import com.lgl.mes.barcode.service.ISpBarcodeService;
import com.lgl.mes.daily.entity.SpDailyPlan;
import com.lgl.mes.digitization.request.spOrderReq;
import com.lgl.mes.group.entity.SpGroup;
import com.lgl.mes.log.entity.SpSysLog;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;
import com.lgl.mes.common.BaseController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 75039960@qq.com
 * @since 2023-12-13
 */
@Controller
@RequestMapping("/barcode")
public class SpBarcodeController extends BaseController {
    //@Autowired
    @Resource
    public ISpBarcodeService iSpBarcodeService;


    /**
     * 设备管理界面
     *
     * @param model 模型
     * @return 设备管理界面
     */
    @ApiOperation("barcodeUI")
    @ApiImplicitParams({@ApiImplicitParam(name = "model", value = "模型", defaultValue = "模型")})
    @GetMapping("/list-ui")
    public String listUI(Model model) {
        return "barcode/list";
    }


    /**
     * 编辑界面barcode
     *
     * @param model  模型
     * @param record 平台表对象
     * @return 更改界面
     */
    @ApiOperation("barcode管理编辑界面")
    @GetMapping("/add-or-update-ui")
    public String addOrUpdateUI(Model model, SpBarcode record) throws Exception {
        if (StringUtils.isNotEmpty(record.getId())) {
            SpBarcode spBarcode = iSpBarcodeService.getById(record.getId());
            model.addAttribute("result", spBarcode);
        }
        return "barcode/addOrUpdate";
    }


    @ApiOperation("barcode批量管理界面")
    @GetMapping("/add-batch-ui")
    public String add_batch_ui(Model model, spBarcodeBatchAddReq req) throws Exception {
        if (req == null ) {

            req = new  spBarcodeBatchAddReq();
            req.setBaseUrl("xxx.com");
            req.setCount(100);
            req.setParam("p=0");
            model.addAttribute("result", req);
        }
        return "barcode/addBatch";
    }

    @SysLog("barcode 批量生成API ")
    @ApiOperation("barcode批量生成API")
    @PostMapping("/addBatch")
    @ResponseBody
    public Result addBatch(/*HttpServletRequest request,@RequestBody */spBarcodeBatchAddReq req) throws Exception {
        iSpBarcodeService.addBatch(/*request,*/req);

        return Result.success();
    }

    //Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported

    /**
     * barcode信息分页查询
     *
     * @param req 请求参数
     * @return Result 执行结果
     */
    @ApiOperation("barcode信息分页查询")
    @ApiImplicitParams({@ApiImplicitParam(name = "req", value = "请求参数", defaultValue = "请求参数")})
    @PostMapping("/page")
    @ResponseBody
    public Result page(spBarcodeReq req) {
        QueryWrapper<SpBarcode> queryWrapper = new QueryWrapper();

        if (StringUtils.isNotEmpty(req.getCodeLike())) {
            queryWrapper.like("code", req.getCodeLike());
        }

        IPage result = iSpBarcodeService.page(req, queryWrapper);
        return Result.success(result);
    }


    /**
     * barcode 新增+修改
     *
     * @param spBarcode
     * @return 执行结果
     */

    //@Async
    @SysLog("barcode新增+修改")
    @ApiOperation("barcode新增+修改")
    @PostMapping("/add-or-update")
    @ResponseBody
    public Result addOrUpdate(/*@RequestBody*/ SpBarcode spBarcode) throws Exception {
        iSpBarcodeService.saveOrUpdate(spBarcode);

        return Result.success();
    }

    /**
     * 删除流程
     *
     * @param req 请求参数
     * @return Result 执行结果
     */
    @SysLog("delete barcode 记录")
    @ApiOperation("delete barcode 记录")
    @ApiImplicitParams({@ApiImplicitParam(name = "req", value = "barcode实体", defaultValue = "barcode实体")})
    @PostMapping("/delete")
    @ResponseBody
    public Result deleteByTableNameId(SpBarcode req) throws Exception {

        iSpBarcodeService.removeById(req.getId());

        return Result.success();
    }



    @ApiOperation("批量删barcode信息")
    @ApiImplicitParams({@ApiImplicitParam(name = "ids", value = "play ids", defaultValue = "plan ids")})
    @PostMapping("/batchDelete")
    @ResponseBody
    public Result batchDelete( String  ids) throws Exception {

        String[] tempList = ids.split(",");
        for (String id  :  tempList)
        {
            iSpBarcodeService.removeById(id);
        }


        return Result.success();
    }



    @SysLog("删除所有二维码")
    @ApiOperation("delete  all 录")
    @ApiImplicitParams({@ApiImplicitParam(name = "req", value = "配置实体", defaultValue = "配置实体")})
    @PostMapping("/allDelete")
    @ResponseBody
    public Result deleteALL(SpSysLog req) throws Exception {
        QueryWrapper<SpBarcode> queryWrapper =new QueryWrapper();

        iSpBarcodeService.remove(queryWrapper);

        BarcodeUtil.deleteFileByIO("images");

        return Result.success();
    }



    //copilot ,帮我检查下这个函数为什么会出现空指针异常？

    //@SysLog("barcode扫码")
    //@Async
    @ApiOperation("barcode扫码")
    @PostMapping("/AntiCodeQueryFunc")
    @ResponseBody
    public Result AntiCodeQueryFunc(@RequestBody  SpBarcode spBarcode) /*throws Exception*/ {
        try {
            String code =spBarcode.getCode();
            System.out.println("AntiCodeQueryFunc code= "+code);
            QueryWrapper<SpBarcode> queryWrapper = new QueryWrapper();
            queryWrapper.eq("code",code);
            List<SpBarcode> list = iSpBarcodeService.list(queryWrapper);
            if(list !=null&&list.size()>0 ){
                  SpBarcode bc = iSpBarcodeService.getById(list.get(0).getId());

                   bc.setQueryTimes(bc.getQueryTimes() + 1);
                    if (bc.getFirstTime() == null) {
                        LocalDateTime now = LocalDateTime.now();
                        bc.setFirstTime(now);
                    }
                   iSpBarcodeService.updateById_lgl(bc);//

                    //iSpBarcodeService.saveOrUpdate(bc);//
                    return Result.success(bc, "success to deal ");
            }
            else {
                return Result.failure("has no  code ");
            }

        } //try
        catch (Exception e) {
           return  Result.failure("查询失败 ，"+e.getMessage());
        }

       // return Result.success(null,"返回数据");
    }

}
